import request from '@/utils/request'
import { defineStore } from 'pinia'
import { IResponse } from '@/types/data'
import { ICategoryItem, ITopCategory, SubCategory } from '@/types/goods'
import { topCategory } from '@/constants'

const defaultCategory = topCategory.map((name) => ({ name }))

export default defineStore('category', {
  state: () => ({
    list: defaultCategory as ICategoryItem[],
    //
    topCategory: {} as ITopCategory,
    subCategory: {} as SubCategory,
  }),
  actions: {
    async getAllCategory() {
      const res = await request.get<IResponse<ICategoryItem[]>>('/home/category/head')
      // #1 给每一个一级分类加一个 open 默认是 false，表示关闭 layer
      res.data.result.forEach((item) => (item.open = false))
      this.list = res.data.result
    },
    // #8 封装根据 id 找到某一个条数据，改变这条数据的 open 的方法
    toggleOpen(id: string, open: boolean) {
      /* const item = this.list.find((item) => item.id === id)
      item!.open = open */
      this.list.find((item) => item.id === id)!.open = open
    },
    async getTopCategory(id: string) {
      const res = await request.get<IResponse<ITopCategory>>('/category', {
        params: {
          id,
        },
      })
      // 把 res.data.result 给了没有指定类型的 topCategory 虽然没有 TS 报错
      // 但是其实后续使用 topCategory 的时候是没有提示的
      this.topCategory = res.data.result
    },
    async getSubFilter(id: string) {
      const res = await request.get<IResponse<SubCategory>>('/category/sub/filter', {
        params: {
          id,
        },
      })
      this.subCategory = res.data.result
    },
  },
})
